package whf.framework.report.jasper;

import java.util.List;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.data.JRAbstractBeanDataSource;

import whf.framework.datasource.DataRow;
import whf.framework.datasource.DataSource;
import whf.framework.meta.entity.IProperty;
import whf.framework.report.ReportUtils;
import whf.framework.util.PropertyUtils;
import whf.framework.util.StringUtils;
import whf.framework.util.Utils;
import whf.framework.web.tag.ext.IColumn;

/**
 * @author wanghaifeng
 * @create Dec 14, 2006 2:40:42 PM
 * 
 */
public class EntityCollectionDataSource extends JRAbstractBeanDataSource{
	private List<DataRow> rows = Utils.newArrayList();
	
	private int position = -1;

	public EntityCollectionDataSource(DataSource<DataRow> dataSource){
		super(true);
		this.rows.addAll(dataSource.getDataSource());
		this.position = -1;
	}
	
	/* (non-Javadoc)
	 * @see net.sf.jasperreports.engine.JRRewindableDataSource#moveFirst()
	 */
	public void moveFirst() throws JRException {
		this.position = -1;
	}

	/* (non-Javadoc)
	 * @see net.sf.jasperreports.engine.JRDataSource#next()
	 */
	public boolean next() throws JRException {
		this.position ++;
		return this.position < this.rows.size();
	}
	
	/* (non-Javadoc)
	 * @see net.sf.jasperreports.engine.data.JRBeanCollectionDataSource#getFieldValue(net.sf.jasperreports.engine.JRField)
	 */
	public Object getFieldValue(JRField field) throws JRException {
		if(this.position == -1) this.position = 0;
		DataRow row = this.position >=0 && this.position < this.rows.size()? this.rows.get(this.position): null;
		if(row == null) return null;
		String property = field.getName();
		IProperty prop = null;
		List<IColumn> columns = ReportUtils.getReportDescriptor().getColumns();
		for(IColumn col: columns){
			if(StringUtils.equals(property, col.getProperty())){
				prop = col.getPropertyObject();
				break;
			}
		}
		return PropertyUtils.translateProperty(row, prop);
	}

}
